import React, { useEffect, useState } from 'react'

import { GetlockersList, getphysical, GetlockTypes, GetAreas, Del_One, Del_Batch } from './service'
import { Action, SearchForm, TableCard, AuthButton } from "../../../components";
import { Table, Select, Input, Button, message, Tag, Popconfirm, Modal } from 'antd';
import { DeleteOutlined, ThunderboltOutlined } from "@ant-design/icons";
import axios from 'axios';
import dayjs from 'dayjs'
import FastCardModel from './FastCardModel'
const { confirm } = Modal;

const SetCard = () => {

    const [dataSource, setDataSource] = useState([]);

    const [Total, setTotal] = useState(0)
    // 加载状态
    const [isFetching, setIsFetching] = useState(false);
    // 物理区
    const [options, setOptions] = useState([]);
    // 柜类型
    const [lockTypes, setLockTypes] = useState([]);
    // 管理区
    const [areas, setAreas] = useState([]);
    // 编辑状态
    const [IsEdit, setIsEdit] = useState(false);
    // 搜索条件
    const [SearchParams, setSearchParams] = useState({
        current: 1,
        pageSize: 10,
        locker_number: "",
        // physical_zone: "",
        area_name: "",
        locker_type: "",
        is_online: ""
    });

    useEffect(() => {
        Getdata(SearchParams)
        // getphysical().then(data => {

        //     setOptions(data.data.map(item => ({                      "guashihao":"3","cardno":"20","clientid":"7221","endtime":1758902400}
        //         label: item.zone_number + "区",   // 显示文本          {"guashihao":"2","cardno":"30","clientid":"7221","endtime":1758902400}
        //         value: item.zone_number,     // 选中值                {"guashihao":"1","cardno":"40","clientid":"7221","endtime":1758902400}
        //     })));
        // })
        GetlockTypes().then(data => {

            setLockTypes(data.data.map(item => ({
                label: item.type_name,   // 显示文本
                value: item.type_name,     // 选中值
            })));
        })
        GetAreas().then(data => {
            // console.log("123", data)
            setAreas(data.data.map(item => ({
                label: item.area_name,   // 显示文本
                value: item.id,     // 选中值
            })));
        })
    }, []);

    const Getdata = (params) => {

        setIsFetching(true)
        GetlockersList(params).then(res => {

            if (!res.data.list.length) {
                setDataSource([])
            }
            setDataSource(res.data.list);

            setTotal(res.data.total)
            setIsFetching(false);
        });
    };

    const handleTableChange = (params) => {

        const newParams = { ...SearchParams, current: params.current, pageSize: params.pageSize };
        Getdata(newParams);
        setSearchParams({ ...SearchParams, ...newParams })
    };

    const [selectionIds, setSelectionIds] = useState([]);
    const rowSelection = {
        onChange: (selectedRowKeys) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`);
            setSelectionIds(selectedRowKeys);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    const SendCard = (record) => {

        let Client = JSON.parse(localStorage.getItem("securityMsg"))
        console.log(Client)
        // return
        let res = {
            "clientid": Client.ID,
            "endtime": dayjs().format("YYYY-MM-DD"),
            "qu": record.physical_zone.toString(),
            "guihao": record.locker_number.toString()
        }

        return new Promise((resolve, reject) => {
            axios({
                url: "http://127.0.0.1:8989/datasnap/rest/TServerMethods1/GSsetcard",
                method: "post",
                data: JSON.stringify(res),
                headers: {
                    "Content-Type": 'application/x-www-form-urlencoded;charset=utf-8',
                    "Accept": "application/json"
                }
            }).then(res => {
                console.log(res)
                if (res.result == 0) {
                    message.success(record.locker_number + "发卡成功")

                    resolve({ code: res.result })
                } else {
                    message.error("发卡失败")
                    reject({ code: -1 })
                }

            }).catch(err => {
                message.error("发卡失败")
            })
        })
    };


    const [isModalOpen, setIsModalOpen] = useState(false);

    return (
        <div>

            <SearchForm>
                <SearchForm.Item span={6} title="柜号">
                    <Input allowClear placeholder="请输入" onChange={(e) => {
                        console.log(e.target.value)
                        Getdata({ ...SearchParams, locker_number: e.target.value })
                        setSearchParams({ ...SearchParams, locker_number: e.target.value })
                    }} />
                </SearchForm.Item>
                {/* 
                <SearchForm.Item span={6} title="物理区">
                    <Select allowClear placeholder="请选择"

                            options={options}
                            onChange={(value) => {
                                Getdata({ ...SearchParams, physical_zone: value })
                                setSearchParams({ ...SearchParams, physical_zone: value })
                                console.log(value)
                            }}></Select>
                </SearchForm.Item> */}

                <SearchForm.Item span={6} title="柜类型">
                    <Select allowClear placeholder="请选择"

                        options={lockTypes}
                        onChange={(value) => {
                            console.log(value)
                            Getdata({ ...SearchParams, locker_type: value })
                            setSearchParams({ ...SearchParams, locker_type: value })
                            console.log(value)
                        }}></Select>
                </SearchForm.Item>
                <SearchForm.Item span={6} title="在线状态">
                    <Select allowClear placeholder="请选择"

                        options={[
                            {
                                label: "在线",
                                value: "true",
                            },
                            {
                                label: "不在线",
                                value: "false",
                            }
                        ]}
                        onChange={(value) => {
                            console.log(value)
                            Getdata({ ...SearchParams, is_online: value })
                            setSearchParams({ ...SearchParams, is_online: value })
                            console.log(value)
                        }}></Select>
                </SearchForm.Item>
                <SearchForm.Item span={6} title="管理区">
                    <Select allowClear placeholder="请选择"

                        options={areas}
                        onChange={(value) => {

                            Getdata({ ...SearchParams, area_name: value })
                            setSearchParams({ ...SearchParams, area_name: value })
                        }}></Select>
                </SearchForm.Item>
                <SearchForm.Item span={6} title="">
                    <Button type="primary">查询</Button> &emsp;
                    <Button type="primary">重置</Button>
                </SearchForm.Item>

            </SearchForm>
            <TableCard
                loading={isFetching}
                rowKey="id"
                dataSource={dataSource}
                onReload={Getdata}
                onTableChange={handleTableChange}
                actions={[
                    <AuthButton type="primary" icon={<ThunderboltOutlined />} onClick={() => { setIsModalOpen(true) }}>
                        快速发卡
                    </AuthButton>
                ]}
                pagination={{
                    showSizeChanger: true,
                    showLessItems: true,
                    showTotal: total => `共 ${Total} 条`,
                    total: Total,
                    current: SearchParams.page,
                    pageSizeOptions: ['10', '20', '50', '100']
                }}
            >
                <Table.Column title="区号" dataIndex="physical_zone" />
                <Table.Column title="区域" dataIndex="locker_user_type" />
                <Table.Column title="柜号" dataIndex="locker_number" />
                <Table.Column title="柜名" dataIndex="locker_name" render={info => (
                    <div>{info == 1 ? "正常" : "异常"}</div>
                )} />
                <Table.Column title="在线状态" dataIndex="is_online"
                    render={info => {

                        return info ? <Tag color="success">在线</Tag > : <Tag color="error">不在线</Tag >
                    }} />
                <Table.Column title="柜类型" dataIndex="locker_product_class" />
                <Table.Column title="柜品种" dataIndex="locker_type" />
                <Table.Column title="规格" dataIndex="locker_spec_name" />
                <Table.Column width={180} title="操作" render={info => (
                    <Action>

                        <Action.Button onClick={() => SendCard(info)}>发设置卡</Action.Button>

                        {/* <Popconfirm placement="top" title={`是否删除柜号${info.locker_number}`} onConfirm={() => {
                            Del_One(info.id).then((res) => {
                                console.log(res)

                                if (res.code == 0) {
                                    message.success("删除成功")
                                    Getdata(SearchParams)
                                } else {
                                    message.error("删除失败")
                                }

                            })
                        }} okText="删除" cancelText="取消">
                            <Action.Button danger


                            >删除</Action.Button>
                        </Popconfirm> */}

                    </Action>
                )} />
            </TableCard>
            {
                isModalOpen && (
                    <FastCardModel SendCard={SendCard} dataSource={dataSource} isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} />
                )
            }

        </div>
    )
}

export default SetCard